package cn.ms.neural;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.ThreadContext;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

public class HelloWorldCommand extends HystrixCommand<String> {

	private final String name;
	private final Map<String, String> threadContextMap=ThreadContext.getContext();

	@SuppressWarnings("deprecation")
	public HelloWorldCommand(String name) {
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory
				.asKey("HelloWorldGroup"))
				.andCommandPropertiesDefaults(
				HystrixCommandProperties.
				Setter().withExecutionIsolationThreadTimeoutInMilliseconds(500)));
		this.name = name;
	}

	protected String getFallback() {
		putThreadContext();
		
		System.out.println("2--->"+Thread.currentThread().getName()+", "+ThreadContext.get("key1"));
		return "exeucute Falled:"+ThreadContext.get("key1");
	}

	protected String run() throws Exception {
		try {
			putThreadContext();
			
			System.out.println("1--->"+Thread.currentThread().getName()+", "+ThreadContext.get("key1"));
			// sleep 1 秒,调用会超时
			TimeUnit.MILLISECONDS.sleep(1000);
			return "Hello " + name + " thread:" + Thread.currentThread().getName()+":"+ThreadContext.get("key1");
		} finally {
			ThreadContext.clearAll();
		}
	}

	private void putThreadContext() {
		if(threadContextMap!=null){
			if(!threadContextMap.isEmpty()){
				for (Map.Entry<String, String> entry:threadContextMap.entrySet()) {
					ThreadContext.put(entry.getKey(), entry.getValue());
				}
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		while (true) {
			ThreadContext.put("key1", "value1");
			System.out.println("0--->"+Thread.currentThread().getName()+", "+ThreadContext.get("key1"));
			HelloWorldCommand helloWorldCommand = new HelloWorldCommand("test-Fallback");
			String result = helloWorldCommand.execute();
			System.out.println("result=" + result);
			Thread.sleep(1000);
		}
	}
}